package com.sl.hx.shop.ui.home;

import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.androidkun.xtablayout.XTabLayout;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sl.hx.shop.R;
import com.sl.hx.shop.base.BaseFragment;
import com.sl.hx.shop.bean.CentralNavigationList;
import com.sl.hx.shop.bean.HomeBannerBean;
import com.sl.hx.shop.bean.HomeGoodBuy;
import com.sl.hx.shop.bean.HomeRecommend;
import com.sl.hx.shop.bean.MessageEvent;
import com.sl.hx.shop.constant.SPUKey;
import com.sl.hx.shop.ui.classify.activity.SearchResultActivity;
import com.sl.hx.shop.ui.home.activity.SearchActivity;
import com.sl.hx.shop.ui.home.activity.SpecialActivity;
import com.sl.hx.shop.ui.home.adapter.BaseFragmentAdapter;
import com.sl.hx.shop.ui.home.adapter.CentraNavigationAdapter;
import com.sl.hx.shop.ui.home.adapter.CommonTabPagerAdapter;
import com.sl.hx.shop.ui.home.contacts.HomeContacts;
import com.sl.hx.shop.ui.home.fragment.GoodsListFragment;
import com.sl.hx.shop.ui.home.presenter.HomePresenter;
import com.sl.hx.shop.utils.FlashSaleUtil;
import com.sl.hx.shop.utils.SPUtils;
import com.sl.hx.shop.utils.ToastUtil;
import com.sl.hx.shop.view.dialog.GuideViewPop;
import com.sl.hx.shop.view.dialog.PpwClipSearch;
import com.sl.hx.shop.view.dialog.PpwSelectPicture;
import com.sl.hx.shop.view.dialog.homeSearchPop;
import com.sl.hx.shop.widget.HeaderScrollView;
import com.sl.hx.shop.widget.StickHeadScrollView;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bingoogolapple.bgabanner.BGABanner;

import static com.sl.hx.shop.utils.ViewVisiable.checkIsVisible;

/**
 * 主页
 */
public class HomeFragment extends BaseFragment<HomeContacts.view, HomePresenter> implements HomeContacts.view {

    @BindView(R.id.banner_guide)
    BGABanner bannerGuide;
    @BindView(R.id.home_iv_search)
    ImageView homeIvSearch;
    @BindView(R.id.scan)
    ImageView scan;
    @BindView(R.id.home_search)
    RelativeLayout homeSearch;
    @BindView(R.id.home_classify)
    RecyclerView homeClassify;
    @BindView(R.id.home_AllSpecial)
    TextView homeAllSpecial;
    @BindView(R.id.home_into)
    ImageView homeInto;
    @BindView(R.id.rl_tag1)
    RelativeLayout rlTag1;
    @BindView(R.id.iv_top)
    ImageView ivTop;
    @BindView(R.id.iv_left)
    ImageView ivLeft;
    @BindView(R.id.iv_center)
    ImageView ivCenter;
    @BindView(R.id.iv_bottom_left)
    ImageView ivBottomLeft;
    @BindView(R.id.iv_bottom_right)
    ImageView ivBottomRight;
    @BindView(R.id.home_tabLayout)
    XTabLayout tabLayout;
    @BindView(R.id.home_viewpager)
    ViewPager viewpager;
    @BindView(R.id.scrollview)
    StickHeadScrollView scrollview;
    @BindView(R.id.rootview)
    LinearLayout rootview;
    @BindView(R.id.refresh)
    SwipeRefreshLayout mRefresh;
    @BindView(R.id.fab)
    ImageView fab;
    @BindView(R.id.countdown_hour)
    TextView mHour;
    @BindView(R.id.countdown_minute)
    TextView mMinute;
    @BindView(R.id.countdown_second)
    TextView mSecond;
    @BindView(R.id.count_down)
    TextView count_down;

    private BaseFragmentAdapter mFragmentAdapter;
    private CommonTabPagerAdapter adapter;
    private CentraNavigationAdapter mCentraNavigationAdapter;
    private Boolean isFirst = true;
    private homeSearchPop pop; //搜索框
    private List<HomeBannerBean> mBannerList;//顶部Banner
    private List<CentralNavigationList> mCentralNavigationLists = new ArrayList<>();//中部导航
    private GuideViewPop guideViewPop;
    private boolean mIsFirstStart; // 是否第一次打开app
    private ClipboardManager clipboardManager;//剪贴板管理器
    private PpwClipSearch mPpwClipSearch;//剪贴板搜索

    @Override
    protected HomePresenter createPresenter() {
        return new HomePresenter(mActivity);
    }

    @Override
    protected int getViewLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView(View mView) {
        refresh();
        //顶部banner
        initBanner();
        //中部导航
        initNavigationList();
        //好惠买
        initGoodBuy();
        initTabLayout();
        initScrollview();
        //引导页
        initGuideView();
        //搜索框
        pop = new homeSearchPop(getContext());
        //根部局加载完毕时,执行
        rootview.getViewTreeObserver().addOnGlobalLayoutListener(mOnGlobalLayoutListener);
        //倒计时
        initCountDown();
    }


    private void initBanner() {
        mBannerList = new ArrayList<>();
        mPresenter.getBanner();
    }

    //中部导航
    private void initNavigationList() {
        mPresenter.getNavigationList();
        mCentraNavigationAdapter = new CentraNavigationAdapter(mCentralNavigationLists);
        homeClassify.setLayoutManager(new GridLayoutManager(mActivity, 5));
        homeClassify.setAdapter(mCentraNavigationAdapter);
        mCentraNavigationAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                mPresenter.indexCount(2, mCentraNavigationAdapter.getItem(position).getId());//点击统计
                mPresenter.NavigationClick(mCentraNavigationAdapter.getItem(position));
            }
        });
    }

    private void initGoodBuy() {
        //1：热销爆款，2：热销排行榜，3：女装上新，4：限时抢购，5：9.9包邮专区
        mPresenter.getHotsell(1);
        mPresenter.getHotlist(2);
        mPresenter.getNewWoman(3);
        mPresenter.getFlashSale(4);
        mPresenter.getFreeShop(5);
    }


    private void initTabLayout() {
        mPresenter.getRecommend();
/*      //避免自动滑动到底部
        tabLayout.setFocusable(true);
        tabLayout.setFocusableInTouchMode(true);
        tabLayout.requestFocus();*//*
        scrollview.resetHeight(tabLayout, viewpager);*/
    }

    private void initScrollview() {
        scrollview.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView nestedScrollView, int i, int i1, int i2, int i3) {
                if (checkIsVisible(getContext(), bannerGuide)) {
                    if (pop.isShowing())
                        pop.dismiss();
                } else {
                    pop.showAtLocation(rootview, Gravity.TOP | Gravity.START, 0, 0);
                }
                int[] position = new int[2];
                tabLayout.getLocationOnScreen(position);
                //状态栏高度
                int result = 0;
                int resourceId = getContext().getResources().getIdentifier("status_bar_height", "dimen", "android");
                if (resourceId > 0) {
                    result = getContext().getResources().getDimensionPixelSize(resourceId);
                }
                if (homeSearch.getHeight() + result >= position[1]) {
                    pop.dismiss();
                    EventBus.getDefault().post(new MessageEvent(true));
                } else {
                    EventBus.getDefault().post(new MessageEvent(false));
                }
            }
        });
    }

    private void refresh() {
        mRefresh.setColorSchemeColors(ContextCompat.getColor(mContext, R.color.main_color));
        mRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPresenter.getBanner();
                mPresenter.getNavigationList();
                initGoodBuy();
                mPresenter.getRecommend();

            }
        });
    }


    //倒计时
    private void initCountDown() {
        long millisInFuture = FlashSaleUtil.initCountDown();
        CountDownTimer timer = new CountDownTimer(millisInFuture, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                // Log.e("long",millisUntilFinished+"");
                int hour = (int) (millisUntilFinished / 1000 / 3600);
                int minute = (int) ((millisUntilFinished / 1000) % 3600 / 60);
                int second = (int) ((millisUntilFinished / 1000) % 60);
                mHour.setText(String.format("%02d", hour));
                mMinute.setText(String.format("%02d", minute));
                mSecond.setText(String.format("%02d", second));
            }

            @Override
            public void onFinish() {
                //倒计时结束时 重新获取
                initCountDown();
            }
        }.start();
    }

    @OnClick({R.id.home_AllSpecial, R.id.home_search, R.id.fab})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //专题页面
            case R.id.home_AllSpecial:
                toActivity(SpecialActivity.class);
                break;
            //搜索页
            case R.id.home_search:
                toActivity(SearchActivity.class);
                break;
            //回到顶部
            case R.id.fab:
                scrollview.fullScroll(ScrollView.FOCUS_UP);
                break;
        }
    }

    //顶部导航
    @Override
    public void ShowBanner(final List<HomeBannerBean> homeBannerBeans) {
        mBannerList.clear();
        if (homeBannerBeans.size() > 0) {
            List<String> url = new ArrayList<>();
            final List<String> map = new ArrayList<>();
            for (HomeBannerBean bannerList : homeBannerBeans) {
                url.add(bannerList.getLogo());
            }
            bannerGuide.setData(url, map);
            //bannerGuide.setVisibility(View.VISIBLE);
            mBannerList.addAll(homeBannerBeans);
            bannerGuide.setAdapter(new BGABanner.Adapter<ImageView, String>() {
                @Override
                public void fillBannerItem(BGABanner banner, ImageView itemView, String model, int position) {
                    Glide.with(mActivity)
                            .load(homeBannerBeans.get(position).getLogo())
                            .apply(RequestOptions.placeholderOf(R.drawable.banenr_bitmap))
                            .into(itemView);
                }
            });
            //导航图点击跳转
            bannerGuide.setDelegate(new BGABanner.Delegate<ImageView, String>() {
                @Override
                public void onBannerItemClick(BGABanner banner, ImageView itemView, String model, int position) {
                    if (position < mBannerList.size()) {
                        mPresenter.BannerClick(mBannerList.get(position), homeBannerBeans, position);
                    }
                }
            });
        } else {
            bannerGuide.setVisibility(View.GONE);
        }
    }

    @Override
    public void ShowNavigationList(List<CentralNavigationList> navigationList) {
        mCentraNavigationAdapter.setNewData(navigationList);
    }

    @Override
    public void ShowRecommend(List<HomeRecommend> recommendList) {
        if (recommendList != null) {
            List<String> mNameList = new ArrayList<>();
            List<Integer> mIdList = new ArrayList<>();
            List<Fragment> mFragmentList = new ArrayList<>();
            for (int i = 0; i < recommendList.size(); i++) {
                mNameList.add(recommendList.get(i).getName());
                mIdList.add(recommendList.get(i).getId());
                mFragmentList.add(createListFragments(recommendList.get(i)));
            }
            if (mFragmentAdapter == null) {
                mFragmentAdapter = new BaseFragmentAdapter(getChildFragmentManager(), mFragmentList, mNameList);
            } else {
                //刷新fragment
                mFragmentAdapter.setFragments(getChildFragmentManager(), mFragmentList, mNameList);
            }
            viewpager.setAdapter(mFragmentAdapter);
            tabLayout.setupWithViewPager(viewpager);
            //MyUtils.dynamicSetTabLayoutMode(tabLayout);
            viewpager.setOffscreenPageLimit(mNameList.size());
            scrollview.resetHeight(tabLayout, viewpager);
        }

        if (mRefresh.isRefreshing()) {
            mRefresh.setRefreshing(false);
        }

    }

    //1：热销爆款
    @Override
    public void ShowHotsell(final HomeGoodBuy goodBuyList) {
        Glide.with(mActivity).load(goodBuyList.getLogo()).apply(RequestOptions.placeholderOf(R.drawable.classify_bitmap)).into(ivBottomLeft);
        ivBottomLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPresenter.HotsellClick(goodBuyList);
            }
        });
    }

    //2：热销排行榜
    @Override
    public void ShowHotlist(final HomeGoodBuy goodBuyList) {
        Glide.with(mActivity).load(goodBuyList.getLogo()).apply(RequestOptions.placeholderOf(R.drawable.banenr_bitmap)).into(ivCenter);
        ivCenter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPresenter.HotlistClick(goodBuyList);
            }
        });
    }

    //3：女装上新
    @Override
    public void ShowNewWoman(final HomeGoodBuy goodBuyList) {
        Glide.with(mActivity).load(goodBuyList.getLogo()).apply(RequestOptions.placeholderOf(R.drawable.vertical_bitmap)).into(ivLeft);
        ivLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPresenter.NewWomanClick(goodBuyList);
            }
        });      }

    //4：限时抢购
    @Override
    public void ShowFlashSale(final HomeGoodBuy goodBuyList) {
        Glide.with(mActivity).load(goodBuyList.getLogo()).apply(RequestOptions.placeholderOf(R.drawable.banenr_bitmap)).into(ivTop);
        ivTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPresenter.FlashSaleClick(goodBuyList);
            }
        });      }

    //5：9.9包邮专区
    @Override
    public void ShowFreeShop(final HomeGoodBuy goodBuyList) {
        Glide.with(mActivity).load(goodBuyList.getLogo()).apply(RequestOptions.placeholderOf(R.drawable.classify_bitmap)).into(ivBottomRight);
        ivBottomRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPresenter.FreeShopClick(goodBuyList);
            }
        });      }

    @Override
    public void ShowRecommendFail() {
        if (mRefresh.isRefreshing()) {
            mRefresh.setRefreshing(false);
        }
    }

    private GoodsListFragment createListFragments(HomeRecommend cateBean) {
        GoodsListFragment fragment = new GoodsListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("goods_id", cateBean.getId());
        bundle.putInt("favorites_id", cateBean.getFavorites_id());
        fragment.setArguments(bundle);
        return fragment;
    }

    //引导页
    private void initGuideView() {
        guideViewPop = new GuideViewPop(getActivity());
        guideViewPop.setOnItemClickListener(new GuideViewPop.OnItemClickListener() {
            @Override
            public void onItemClick(View v) {
                switch (v.getId()) {
                    case R.id.guide_view_bottom:
                        guideViewPop.dismiss();
                        break;
                }
            }
        });
    }

    ViewTreeObserver.OnGlobalLayoutListener mOnGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            mIsFirstStart = SPUtils.getInstance().getBoolean(SPUKey.ISFIRSTLAUNCH, true);
            if (mIsFirstStart) {
                guideViewPop.showAtLocation(rootview, Gravity.CENTER, 0, 0);
                guideViewPop.setBackgroundAlpha(getActivity(), 0.3f);
                SPUtils.getInstance().put(SPUKey.ISFIRSTLAUNCH, false);
            } else {
                getTextFromClip();
            }
            rootview.getViewTreeObserver().removeGlobalOnLayoutListener(mOnGlobalLayoutListener);
        }
    };

    public void getTextFromClip() {
        clipboardManager = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clipData = clipboardManager.getPrimaryClip();
        if (clipData == null) {
            return;
        }
        //获取 text
        String text = clipData.getItemAt(0).getText().toString();
        if (text.length()>=16) {
            initClipSearch(text.substring(0,15));//取前15位
            //将剪贴板内容设置空,下次进来不搜索
            clipboardManager.setPrimaryClip(ClipData.newPlainText("text",""));
        }

        //clipboardManager.setPrimaryClip(null);
    }

    private void initClipSearch(final String text) {
        mPpwClipSearch = new PpwClipSearch(mContext, text);
        mPpwClipSearch.showAtLocation(rootview, Gravity.CENTER, 0, 0);
        mPpwClipSearch.setBackgroundAlpha(mActivity, 0.35f);
        mPpwClipSearch.setOnItemClickListener(new PpwClipSearch.OnItemClickListener() {
            @Override
            public void onItemClick(View v) {
                switch (v.getId()) {
                    case R.id.close:
                        mPpwClipSearch.dismiss();
                        break;
                    case R.id.search:
                        mPpwClipSearch.dismiss();
                        Intent intent = new Intent(mActivity, SearchResultActivity.class);
                        intent.putExtra("searchTitle", text);
                        startActivity(intent);
                        break;
                }
            }
        });
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            if (pop.isShowing())
                pop.dismiss();
        }
    }

}
